package net.begincode.maiev.monitor;

import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 封装线程池(单例封装)
 * Created by Stay on 2017/3/18  14:07.
 */
public class ThreadPool {
    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors(),
            0L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingDeque<Runnable>());

    private static class SingletonHolder {
        private static final ThreadPool INSTANCE = new ThreadPool();
    }

    private ThreadPool() {
    }

    public static final ThreadPool getInstance() {
        return SingletonHolder.INSTANCE;
    }


    public void addTask(Runnable runnable) {
        executor.execute(runnable);
    }

    public void addTask(Callable callable) {
        executor.submit(callable);
    }

    public boolean waitTask(long timeout, TimeUnit unit) {
        try {
            return executor.awaitTermination(timeout, unit);
        } catch (InterruptedException e) {
            //
        }
        return false;
    }

    public Integer getActiveTask() {
        return executor.getActiveCount();
    }

    public boolean isTerminated() {
        return executor.isTerminated();
    }


}
